<?php
namespace Users\Controller;

use Think\Controller;
class LoginController extends Controller{
	private $sms;
	private $smsLogic;
	private $loginService;
	private $user;
	private $connect;
	private $email;
	private $regService;
	private $invitation;
	
	function _initialize(){
		$this->sms = D('Sms');
		$this->smsLogic = D('Sms','Logic');
		$this->loginService = D('Login','Service');
		$this->user = D('Users');
		$this->connect = D('Connect','Service');
		$this->email = D('Email');
		$this->regService = D('Reg','Service');
		$this->invitation = D('UsersInvitation');
		
		//判断是否有cookie自动登录
		$this->loginService->cookielogin();
	}
	
	/**
	 * 获取返回地址
	 */
	protected function getgoto(){
		$goto = $_SERVER['HTTP_REFERER'];
		$host = 'http://'.$_SERVER['HTTP_HOST'];
		if(!$goto){
			$goto = $host;
		}
		//地址过滤
		$guolvs = array('/Users/login','/Users/register','/Users/resetpwd','/Users/Member');
		
		foreach($guolvs as $gl){
			if(strpos($goto, $gl)){
				$goto =  $host;
				break;
			}
		}
		return $goto;
	}

	//登录页面
	public function index(){
		session('logincode',md5(uniqid().rand(0,100000))); //生成登录待校验的code
		$next = I('get.next');
		if(!$next){
			$url = '/users/login/index?next='.urlencode($this->getgoto());
			header("location:".$url);
			exit();
		}else{
			session('goto',$next);
		}
		
		$this->display();
	}
	
	/**
	 * 获取登录校验码
	 */
	public function getlogincode(){
		if(session('logincode')){
			_apiReturn(1, '获取成功', session('logincode'), $url);
		}else{
			_apiReturn(0, '登录校验码不存在', $data, $url);
		}
	}
	
	public function login_post(){
		if(IS_POST){
			if($_POST['loginCode']){
				$result = false;
				if(session('logincode') == $_POST['loginCode']){
					//session('logincode',null);//销毁登录校验码，防止被重复被利用
					$result = TRUE;
				}
				if($result == TRUE){
					$user = trim($_POST['username']);
					$pwd = md5(trim($_POST['pwd']));
					$remember = $_POST['_remember_me']?1:0;
					$ret = $this->loginService->login($user,$pwd,$remember);
					if($ret == 1){
						$url = U('Member/index');
						if(session('goto')){
							$url = session('goto');
							session('goto',null);
						}
						$this->success('登录成功','/admin.html');
					}else if($ret == -1){
						$this->error('密码错误');
					}else if($ret == -2){
						$this->error('用户名或手机不存在');
					}else if($ret == -3){
						$this->error('角色不匹配,无法登录');
					}else{
						$this->error('登录失败');
					}
				}else {
					$this->error('验证码错误');
				}
			}else{
				$this->error('请先拖动滑块验证');
			}
		}
	}
	
	//注册方法
	public function register_post(){
		if(IS_POST){
			
			if($this->smsLogic->_check_code(trim($_POST['register']['mobile']),trim($_POST['register']['sms_code']),'register')){
				
				//判断邀请码是否正确
				if(C('INVITATION_SWITCH')){
					$invitation = I('post.invitation');
					//$info = $this->regService->checkInvitation($invitation);
					//if(!$info){
					//	$this->error('邀请码已被使用');
					//	exit();
					//}
				}
				
				$mobile = trim($_POST['register']['mobile']);
				$username = trim($_POST['register']['name']);
				$pwd = md5(trim($_POST['register']['pwd']));
				$role = 'ROLE_ADMIN';
				if($this->loginService->add($username,$pwd,$mobile,$role)){
					if(C('INVITATION_SWITCH')){
						$this->regService->useInvitation($invitation);
					}
					$this->success('注册成功',U('admin/index/index'));
				}else{
					$this->error('注册失败');
				}
			}else{
				$this->error('短信验证码错误或已过期');
			}
			
		}
	}
	
	//发送验证码
	public function sendsms(){
		if(IS_POST){
			$mobile = I('post.mobile');
			$code = rand(100000,999999);
			$type = I('post.type');
			if($this->smsLogic->_send_sms($mobile,$code,$type)){
				$this->success('发送成功');
			}else{
				$this->error('发送失败');
			}
		}
	}
	
	//验证mobile，username字段是否为一
	public function check(){
		$t = I('get.t');
		if($t === 'mobile'){
			$value = $_REQUEST['register']['mobile'];
			$str_ok = '';
			$str_error = '手机号码已存在';
		}else if($t === 'username'){
			$value = $_REQUEST['register']['name'];
			$str_ok = '';
			$str_error = '用户名已存在';
		}
		$map[$t] = $value;
		if(!$this->user->where($map)->find()){
			$data['ok'] = $str_ok;	
		}else{
			$data['error'] = $str_error;
		}
		$this->ajaxReturn($data,'JSON');
	}
	
	//判断手机号码是否存在
	public function checkhas(){
		$t = I('get.t');
		if($t === 'mobile'){
			$value = $_REQUEST['mobile'];
			$str_ok = '';
			$str_error = '手机号码不存在';
		}else if($t === 'email'){
			$value = $_REQUEST['email'];
			$str_ok = '';
			$str_error = '邮箱不存在';
		}
		$map[$t] = $value;
		if($this->user->where($map)->find()){
			$data['ok'] = $str_ok;
		}else{
			$data['error'] = $str_error;
		}
		$this->ajaxReturn($data,'JSON');
	}
	
	public function resetpwd_post(){
		if(IS_POST){
			if($this->smsLogic->_check_code(trim($_POST['mobile']),trim($_POST['sms_code']),'resetpwd')){
				$map['mobile'] = trim($_POST['mobile']);
				$data['password'] = md5(trim($_POST['pwd']));
				$data['update_time'] = Date('Y-m-d H:i:s');
				if($this->user->where($map)->save($data)){
					$this->success('密码重设成功,请重新登录',U('Login/index'));
				}else{
					$this->error('密码重设失败');
				}
			}else{
				$this->error('验证码错误或已过期');
			}
		}
	}
	
	public function emailforpwd_post(){
		if(IS_POST){
			$email = I('post.email');
			$token = md5($email.time());
			$token_time =  time()+60*60*24;//24小时后过期
			
			$sendemail = new \Users\Service\EmailService();
			$title = "这是一封找回密码的邮件";
			$href = 'http://'.$_SERVER['HTTP_HOST'].U('resetpwd/editpwdforemail',array('token'=>$token));
			$body = "<a href='".$href."'>".$href."</a>";
			if($sendemail->sendemail($email, $title, $body)){
				//TODO发送邮件后保存发送信息
				$data['email'] = $email;
				$data['token'] = $token;
				$data['token_time'] = $token_time;
				$data['type'] = 'retrievepwd';
				$data['create_time'] = Date('Y-m-d H:i:s');
				$this->email->add($data);
				
				$this->success('发送成功',U('index'));
			}else{
				$this->error('发送失败');
			}
		}
	}
	
	public function editpwdforemail_post(){
		if(IS_POST){
			$data['password'] = md5(trim($_POST['pwd']));
			$map['email'] = $_POST['email'];
			if($this->user->where($map)->save($data)){
				$this->success('修改密码成功,请重新登录',U('index'));
			}else{
				$this->error('修改密码失败');
			}
		}
	}
	
	
	
	//第三方授权登录
	public function connect($type){
		empty($type) && $this->error('参数错误');
		//动态加载配置
		$this->connect->getConfig($type);
	
		//加载ThinkOauth类并实例化一个对象
		$sns  = \Org\ThinkSDK\ThinkOauth::getInstance($type);
		//跳转到授权页面
		redirect($sns->getRequestCodeURL());
	}
	
	//授权回调地址
	public function callback($type = null, $code = null){
		(empty($type) || empty($code)) && $this->error('参数错误');
		
		//动态加载配置
		$this->connect->getConfig($type);

		//加载ThinkOauth类并实例化一个对象
		$sns  = \Org\ThinkSDK\ThinkOauth::getInstance($type);
	
		//腾讯微博需传递的额外参数
		$extend = null;
		if($type == 'tencent'){
			$extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey'));
		}
	
		//请妥善保管这里获取到的Token信息，方便以后API调用
		//调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
		//如： $qq = ThinkOauth::getInstance('qq', $token);
		$token = $sns->getAccessToken($code , $extend);
	
		//获取当前登录用户信息
		if(is_array($token)){
			$user_info = $this->connect->$type($token);
	
			echo("<h1>恭喜！使用 {$type} 用户登录成功</h1><br>");
			echo("授权信息为：<br>");
			dump($token);
			echo("当前登录用户信息为：<br>");
			dump($user_info);
		}
	}
}